//
//  FP_OrderUploadPicCell.m
//  FootPad
//
//  Created by 张浩 on 2021/12/2.
//  Copyright © 2021 胶享悦. All rights reserved.
//

#import "MM_CodeResultListPicCell.h"
#import "MM_UploadPicView.h"
#import "MM_AlertView.h"
#import "SDPhotoBrowser.h"

static const NSInteger AddTag = 100000;
static const NSInteger MaxPicCount = 1000000;
static const NSInteger maxCountOfRow = 6;

@interface MM_CodeResultListPicCell ()<SDPhotoBrowserDelegate>

@property (nonatomic, strong) UIView *baseView;
@property (nonatomic, strong) UIButton *addPicBtn;

@end

@implementation MM_CodeResultListPicCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        _baseView = [[UIView alloc] init];
        [self.contentView addSubview:_baseView];
                        
        _addPicBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addPicBtn setImage:[UIImage imageNamed:@"addUploadPicImage"] forState:UIControlStateNormal];
        _addPicBtn.layer.cornerRadius = 10;
        _addPicBtn.layer.masksToBounds = YES;
        _addPicBtn.layer.borderColor = [ColorUtil colorWithHexadecimal:@"#707070"].CGColor;
        _addPicBtn.layer.borderWidth = 0.5;
        _addPicBtn.hidden = NO;
        [_addPicBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.baseView addSubview:_addPicBtn];
        
        [self setConstraint];
    }
    return self;
}

- (void)setConstraint {
    
    [self.baseView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.bottom.right.equalTo(self.contentView);
    }];

}

- (void)setModel:(MM_CodeResultListPicModel *)model {
    _model = model;
    
    [self uploadTagValue];
    [self uploadSubView];
    
    CGFloat space = 10;
    CGFloat picY = 10;
    CGFloat picH = 10;
    
    CGFloat relationSubViewW = (ScreenW - space*(maxCountOfRow+1))/maxCountOfRow;
    CGFloat relationSubViewH = relationSubViewW;
    
    NSInteger count = self.model.imageArr.count;
    
    if (count > 0) {
        
        for (NSInteger i=0; i<count; i++) {
            MM_UploadImageModel *addImageModel = self.model.imageArr[i];
            MM_UploadPicView *UploadPicView = (MM_UploadPicView *)[self.baseView viewWithTag:i + AddTag];
            if (!UploadPicView) {
                UploadPicView = [[MM_UploadPicView alloc] init];
                UploadPicView.tag = i+AddTag;
                UploadPicView.layer.cornerRadius = 10;
                UploadPicView.layer.masksToBounds = YES;
                [self.baseView addSubview:UploadPicView];
                //回调block
                [self addBlockWithPicView:UploadPicView];
            }
            UploadPicView.frame = CGRectMake(12 + (relationSubViewW + space)*(i%6), picY+(relationSubViewH + space)*(i/6), relationSubViewW, relationSubViewH);
            if (addImageModel) {
                if (addImageModel.canUploadImage) {
                    if (addImageModel.tempImage) {
                        addImageModel.canUploadImage = NO;
                        UploadPicView.imageModel = addImageModel;
                        [UploadPicView startUploadPic];
                    }else {
                        UploadPicView.imageModel = addImageModel;
                    }
                }else {
                    UploadPicView.imageModel = addImageModel;
                }
            }
        }
    }else {
        
        for (UIView *subView in self.baseView.subviews) {
            
            if ([subView isKindOfClass:[MM_UploadPicView class]]) {
                [subView removeFromSuperview];
            }
        }
    }
    
    _addPicBtn.hidden = (count == MaxPicCount);
    NSInteger btnCount = _addPicBtn.hidden?count-1:count;
    CGRect addBtnFrame = CGRectMake(10 + (relationSubViewW + space)*(btnCount%6), picY+(relationSubViewH + space)*(btnCount/6), relationSubViewW, relationSubViewH);
    _addPicBtn.frame = addBtnFrame;
    
    model.cellHeight = CGRectGetMaxY(addBtnFrame) + picH;
}

/*******重新计算tag值**********/
- (void)uploadTagValue {
    
    NSInteger add = 0 ;
    for (UIView * subView in self.baseView.subviews) {
        if ([subView isKindOfClass:[MM_UploadPicView class]]) {
            MM_UploadPicView *jhUploadPic = (MM_UploadPicView *)subView;
            jhUploadPic.tag = add+AddTag;
            add++;
        }
    }
}

- (void)uploadSubView {
    
    for (UIView *subView in self.baseView.subviews) {
        
        if ([subView isKindOfClass:[MM_UploadPicView class]]) {
            
            MM_UploadPicView *uploadPicView = (MM_UploadPicView *)subView;
            [uploadPicView removeFromSuperview];
        }
    }
}

- (void)addBlockWithPicView:(MM_UploadPicView *)jhUploadPic {
    
    __weak typeof(self)weakSelf = self;
    __weak MM_UploadPicView *weakPicView = jhUploadPic;
    [jhUploadPic setSuccessBlock:^(NSDictionary * _Nonnull userImageModel) {
        //通过回调的数据再次发送请求
        NSLog(@"responseDic = %@",userImageModel);
    } failBlock:^(NSString *message) {
        NSLog(@"message = %@",message);
        [MM_PublicHUD showStateText:message];
        
    } tapPicBlock:^{
        NSLog(@"点击图片");
        
        SDPhotoBrowser *photoBrowser = [[SDPhotoBrowser alloc]init];
        photoBrowser.delegate = weakSelf;
        photoBrowser.currentImageIndex = weakPicView.tag - AddTag;
        photoBrowser.imageCount = weakSelf.model.imageArr.count;
        photoBrowser.sourceImagesContainerView = weakSelf.baseView;
        [photoBrowser show];
        
    } deletePicBlock:^(MM_UploadPicView * picView){
        NSLog(@"删除图片");
        [picView clearnPicViewRequest];
        
        [MM_AlertView MM_AlertWithTitle:@"" message:@"是否删除图片?" withJH_AlertBlock:^(MM_AlertViewBtnType buttonIndexType) {
      
            
            if (buttonIndexType == MM_AlertViewBtnTypeEnsure) {
                if (weakSelf.deleteBlock) {
                    weakSelf.deleteBlock(picView.imageModel);
                }
                [weakSelf deletePicView:picView];
            }
        } cancelButtonTitle:@"取消" ensureButtonTitle:@"确定"];
        
    } errorPicBlock:^{
        NSLog(@"出错点击图片");
        
        [MM_AlertView MM_AlertWithTitle:@"" message:@"图片上传失败，是否重新上传" withJH_AlertBlock:^(MM_AlertViewBtnType buttonIndexType) {
            
            if (buttonIndexType == MM_AlertViewBtnTypeEnsure) {
                [weakPicView startUploadPic];
            }
        } cancelButtonTitle:@"取消" ensureButtonTitle:@"确定"];
        
    }];
}

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index {
    
    MM_UploadImageModel *imageModel = self.model.imageArr[index];
    return [NSURL URLWithString:imageModel.img];
}

- (void)deletePicView:(MM_UploadPicView *)picView {
    [self.model.imageArr removeObject:picView.imageModel];
    [picView removeFromSuperview];
}

- (void)btnClick:(UIButton *)btn {
    
    if (self.addPicBlock) {
        self.addPicBlock();
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
